//
//  SleepAnalysisViewController.m
//  Health
//
//  Created by LeeJay on 16/8/29.
//  Copyright © 2016年 LeeJay. All rights reserved.
//

#import "SleepAnalysisViewController.h"
#import <HealthKit/HealthKit.h>

@interface SleepAnalysisViewController ()

@property (nonatomic, assign) NSTimeInterval startTime;
@property (nonatomic, strong) NSDate *endTime;
@property (nonatomic, strong) NSDate *alarmTime;
@property (nonatomic, strong) NSTimer *timer;
@property (weak, nonatomic) IBOutlet UILabel *displayTimeLabel;

@end

@implementation SleepAnalysisViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (IBAction)start:(id)sender
{
    self.alarmTime = [NSDate date];
    if (!self.timer.valid) {
        [self updateTime];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
        _startTime = [NSDate timeIntervalSinceReferenceDate];
    }
}

- (IBAction)stop:(id)sender
{
    _endTime = [NSDate date];
    [self saveSleepAnalysis];
    [self retrieveSleepAnalysis];
    [_timer invalidate];

}

- (void)updateTime
{
    NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
    
    NSTimeInterval elapsedTime = currentTime - _startTime;
   
    NSInteger minutes = elapsedTime / 60;
    elapsedTime -= minutes * 60;
    
    NSInteger seconds = elapsedTime;
    elapsedTime -= seconds;
    
    NSInteger fraction = elapsedTime * 100;
    
    NSString *strMinutes = [NSString stringWithFormat:@"%02zd",minutes];
    NSString *strSeconds = [NSString stringWithFormat:@"%02zd",seconds];
    NSString *strFraction = [NSString stringWithFormat:@"%02zd",fraction];
    
    self.displayTimeLabel.text = [NSString stringWithFormat:@"%@:%@:%@",strMinutes,strSeconds,strFraction];
}

- (void)saveSleepAnalysis
{
    HKCategoryType *sleepType =  [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
    if (sleepType) {
        HKCategorySample *object = [HKCategorySample categorySampleWithType:sleepType value:HKCategoryValueSleepAnalysisInBed startDate:self.alarmTime endDate:self.endTime];
        [self.healthStore saveObject:object withCompletion:^(BOOL success, NSError * _Nullable error) {
            
            if (error != nil) {
                return;
            }
            
            if (success) {
                NSLog(@"My new data was saved in Healthkit");
            } else {

            }
            
        }];
        
         HKCategorySample *object2 = [HKCategorySample categorySampleWithType:sleepType value:HKCategoryValueSleepAnalysisAsleep startDate:self.alarmTime endDate:self.endTime];
        [self.healthStore saveObject:object2 withCompletion:^(BOOL success, NSError * _Nullable error) {
            if (error != nil) {
                return;
            }
            
            if (success) {
                NSLog(@"My new data (2) was saved in Healthkit");
            } else {
                
            }

        }];
    }
}

- (void)retrieveSleepAnalysis
{
    HKSampleType *sleepType = [HKObjectType categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis];
    
    if (sleepType) {
        NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:HKSampleSortIdentifierEndDate ascending:NO];
        HKSampleQuery *query = [[HKSampleQuery alloc] initWithSampleType:sleepType predicate:nil limit:30 sortDescriptors:@[sortDescriptor] resultsHandler:^(HKSampleQuery * _Nonnull query, NSArray<__kindof HKSample *> * _Nullable results, NSError * _Nullable error) {
            
            if (error != nil) {
                
                return;
            }
           
            NSArray *new_results = results;
            
            if (new_results) {
                for (HKSample *item in new_results) {
                    HKCategorySample *sample = (HKCategorySample *)item;
                    if (sample) {
                        NSString *value = sample.value == HKCategoryValueSleepAnalysisInBed ? @"InBed" : @"Asleep";
                        NSLog(@"Healthkit sleep: %@ %@ - value: %@",sample.startDate, sample.endDate, value);
                    }
                }
            }
        }];
        
        [self.healthStore executeQuery:query];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
